#!/bin/sh

BUILD_DIR=$INSTALL_DIR
NAME=$PRODUCT_NAME
PROVIDES=$PRODUCT_NAME
PKG_ARCH=arm

echo $NAME | grep -e "[[:upper:]]" &> /dev/null
if [ $? -eq 0 ]; then
  echo -e "*** Warning: The package name \"$NAME\" contains upper case\n*** Warning: letters. dpkg might not like that so I changed\n*** Warning: them to lower case."
  NAME=`echo $NAME | tr 'A-Z' 'a-z'`
fi

[ -n "$APP_SUBNAME" ] && PROVIDES="$PRODUCT_NAME"_"$APP_SUBNAME"

SUBREPO_PATH=$(LANG=C svn info | awk '{ if ($1=="URL:") print $2; }' | sed 's/^[ \t]*//g')
RELEASE=$(LANG=C svn info $SUBREPO_PATH | awk -F: '{ if ($1 == "Last Changed Rev") print $2; }' | sed 's/^[ \t]*//g')

# We'll write a basic Debian control file
mkdir $BUILD_DIR/DEBIAN 2>/dev/null

cat << EOF | sed "s/ $//" | egrep ": " >> $BUILD_DIR/DEBIAN/control
Package: $NAME
Priority: extra
Section: SunplusAPP
Installed-Size: `du -s $BUILD_DIR | awk '{print $1}'`
Maintainer: ${LOGNAME:-root}@${MAINTDOMAIN}
Architecture: $PKG_ARCH
Version: $VERSION-$RELEASE
Provides: $PROVIDES
Conflicts: $CONFLICTS
Replaces: $REPLACES
Description: $PROVIDES-$VERSION-$RELEASE
EOF

# Add the description
#if [ -f description-pak ]; then
#	cat "description-pak" | egrep -v "$SUMMARY|^[ 	]*$" | while read line; do
#	   echo " "$line >> $BUILD_DIR/DEBIAN/control
#	done
#fi

# Use the preinstall-pak script if we have it
if [ -f preinstall-pak ]; then
   cat preinstall-pak > $BUILD_DIR/DEBIAN/preinst
   chmod 755 $BUILD_DIR/DEBIAN/preinst
fi

# Use the postinstall-pak script if we have it
if [ -f postinstall-pak ]; then
   cat postinstall-pak > $BUILD_DIR/DEBIAN/postinst
   chmod 755 $BUILD_DIR/DEBIAN/postinst
fi

# Use the preremove-pak script if we have it
if [ -f preremove-pak ]; then
   cat preremove-pak > $BUILD_DIR/DEBIAN/prerm
   chmod 755 $BUILD_DIR/DEBIAN/prerm
fi

# Use the postremove-pak script if we have it
if [ -f postremove-pak ]; then
   cat postremove-pak > $BUILD_DIR/DEBIAN/postrm
   chmod 755 $BUILD_DIR/DEBIAN/postrm
fi

# Tag files in /etc to be conffiles
find -L $BUILD_DIR/etc -type f 2> /dev/null | sed -e "s,$BUILD_DIR,," | \
        > $BUILD_DIR/DEBIAN/conffiles

# The package will be saved here (ignores <epoch>: prefix):
DEBPKG="${NAME}_`echo ${VERSION} | sed -e 's/^[0123456789]*://'`-${RELEASE}_${PKG_ARCH}.deb"

echo "Building Debian package..."
dpkg-deb -b $BUILD_DIR "$DEBPKG"

echo "Cleaning up..."
rm -rf $BUILD_DIR/DEBIAN
